/**
 * Created by 赵波 on 2021/6/11.
 * 文章路由
 */
var router = require('koa-router')();
var userModel = require('../lib/mysql.js');
var moment = require('moment');
const session = require('koa-session-minimal');

router.get('/', async(ctx, next) => {
    ctx.redirect('/posts');
});
router.get('/admintalk', async(ctx, next) => {
    await ctx.render('admintalk', {
        session: ctx.session
    })
})
router.get('/admintalk/:postId', async(ctx, next) => {
    console.log(ctx.params.postId);
    // 通过文章id查找返回数据，然后增加pv 浏览 +1
    await userModel.findDataById(ctx.params.postId)
        .then(result => {
            res = JSON.parse(JSON.stringify(result));
            res_pv = parseInt(JSON.parse(JSON.stringify(result))[0]['pv']);
            res_pv += 1;
            console.log(res);
        });
    await userModel.updatePostPv([res_pv, ctx.params.postId]);
    await userModel.findCommentById(ctx.params.postId)
        .then(result => {
            comment_res = JSON.parse(JSON.stringify(result));
        });
    await userModel.fingCommentCount(ctx.params.postId).then(result => {
        comment_count = parseInt(JSON.parse(JSON.stringify(result))[0]['num']);
    });
    await ctx.render('admintalk', {
        session: ctx.session,
        posts: res,
        comments: comment_res,
        number: comment_count
    });
});
//管理员全部文章页面，点击某一个会跳转到某个文章界面
router.get('/adminpost', async(ctx, next) => {
    // 如果请求参数存在的话
    if (ctx.request.querystring) {
        console.log('ctx.request.querystring', decodeURIComponent(ctx.request.querystring.split('=')[1]));
        await userModel.findDataByUser(decodeURIComponent(ctx.request.querystring.split('=')[1]))
            .then(result => {
                res = JSON.parse(JSON.stringify(result));
                console.log(res);
            });
        await ctx.render('adminpost', {
            session: ctx.session,
            posts: res
        });
    } else {
        await userModel.findAllPost().then(result => {
            console.log(result);
            res = JSON.parse(JSON.stringify(result));
            console.log(res);
        });
        await ctx.render('adminpost', {
            session: ctx.session,
            posts: res
        });
    }
});
// 管理员查看所有的悬赏贴子
router.get('/adminxspost', async(ctx, next) => {
    // 点击查看单个用户的所有的文章
    if (ctx.request.querystring) {
        console.log('ctx.request.querystring', decodeURIComponent(ctx.request.querystring.split('=')[1]));
        await userModel.findxsAllDataByUser(decodeURIComponent(ctx.request.querystring.split('=')[1]))
            .then(result => {
                res = JSON.parse(JSON.stringify(result));
                console.log(res);
            });
        await ctx.render('adminxs', {
            session: ctx.session,
            posts: res,
        });
    } else {
        await userModel.findAllxs().then(result => {
            console.log(result);
            res = JSON.parse(JSON.stringify(result));
            console.log(res);
        });

        await ctx.render('adminxs', {
            session: ctx.session,
            posts: res
        });
    }
});
// 管理员查看单个悬赏贴内容，
router.get('/adminxspost/:postId', async(ctx, next) => {
    console.log(ctx.params.postId + "我来了。。。。");
    // 通过文章id查找返回数据，然后增加pv 浏览 +1
    await userModel.findxsDataById(ctx.params.postId)
        .then(result => {
            res = JSON.parse(JSON.stringify(result));
            res_pv = parseInt(JSON.parse(JSON.stringify(result))[0]['pv']);
            res_pv += 1;
            console.log(res);
        });
    await userModel.updatexsPostPv([res_pv, ctx.params.postId]);

    await ctx.render('adminxspost', {
        session: ctx.session,
        posts: res,
    });
});
//全部文章页面
router.get('/posts', async(ctx, next) => {
    if (ctx.request.querystring) {
        console.log('ctx.request.querystring', decodeURIComponent(ctx.request.querystring.split('=')[1]));
        await userModel.findDataByUser(decodeURIComponent(ctx.request.querystring.split('=')[1]))
            .then(result => {
                res = JSON.parse(JSON.stringify(result));
                console.log(res);
            });
        await ctx.render('posts', {
            session: ctx.session,
            posts: res
        });
    } else {
        await userModel.findAllPost().then(result => {
            console.log(result);
            res = JSON.parse(JSON.stringify(result));
            console.log(res);
        });
        await ctx.render('posts', {
            session: ctx.session,
            posts: res
        });
    }
});
//发表文章页面
router.get('/create', async(ctx, next) => {
    await ctx.render('create', {
        session: ctx.session
    })
});
//发表文章
router.post('/create', async(ctx, next) => {
    console.log(ctx.session.user);
    var title = ctx.request.body.title;
    var content = ctx.request.body.content;
    var id = ctx.session.id;
    var name = ctx.session.user;
    var time = moment().format('YYYY-MM-DD HH:mm');
    console.log([name, title, content, id, time]);
    await userModel.insertPost([name, title, content, id, time]).then(() => {
        console.log(name + '发表文章' + title + '成功');
        ctx.body = 'true';
    }).catch(() => {
        console.log('发表文章失败');
        ctx.body = 'false';
    });
});
// 悬赏贴
router.get('/createup', async(ctx, next) => {
    await ctx.render('createup', {
        session: ctx.session
    })
});
//悬赏贴文章
router.post('/createup', async(ctx, next) => {
    console.log(ctx.session.user);
    var title = ctx.request.body.title;
    var content = ctx.request.body.content;
    var id = ctx.session.id;
    var name = ctx.session.user;
    var time = moment().format('YYYY-MM-DD HH:mm');
    var money = ctx.request.body.money
    console.log([name, title, content, id, time, money]);
    await userModel.insertxsPosts([name, title, content, id, time, money]).then(() => {
        console.log(name + '发表悬赏' + title + '成功');
        ctx.body = 'true';
    }).catch(() => {
        console.log('发表悬赏失败');
        ctx.body = 'false';
    });
});
//全部悬赏
router.get('/xsposts', async(ctx, next) => {
    // 点击查看单个用户的所有的文章
    if (ctx.request.querystring) {
        console.log('ctx.request.querystring', decodeURIComponent(ctx.request.querystring.split()));
        await userModel.findxsAllDataByUser(decodeURIComponent(ctx.request.querystring.split('=')[1]))
            .then(result => {
                res = JSON.parse(JSON.stringify(result));
                console.log(res);
            });

        await ctx.render('xsposts', {
            session: ctx.session,
            posts: res
        });
    } else {
        await userModel.findAllxsPosts().then(result => {
            console.log(result);
            res = JSON.parse(JSON.stringify(result));
            console.log(res);
        });

        await ctx.render('xsposts', {
            session: ctx.session,
            posts: res
        });
    }
});
// 查看单片悬赏贴
router.get('/xsposts/:postId', async(ctx, next) => {
    console.log(ctx.params.postId);
    // 通过文章id查找返回数据，然后增加pv 浏览 +1
    await userModel.findxsDataById(ctx.params.postId)
        .then(result => {
            res = JSON.parse(JSON.stringify(result));
            res_pv = parseInt(JSON.parse(JSON.stringify(result))[0]['pv']);
            res_pv += 1;
            console.log(res);
        });
    await userModel.updatexsPostPv([res_pv, ctx.params.postId]);

    await ctx.render('xspost', {
        session: ctx.session,
        posts: res,
    });
});
// 接取悬赏
router.get('/accept', async(ctx, next) => {
    await ctx.render('accept', {
        session: ctx.session
    })
});
//接取悬赏
router.post('/accept', async(ctx, next) => {
    console.log(ctx.session.user);
    var name = ctx.request.body.name;
    var phonenum = ctx.request.body.phonenum;
    var uid = ctx.session.id
    var id = ctx.request.body.num;
    console.log([name, phonenum, id]);
    await userModel.insertAccept([name, phonenum, uid, id]).then(() => {
        userModel.updateAcceptPost(id)
        console.log(name + '接取' + id + '成功');
        ctx.body = 'true';

    }).catch(() => {
        console.log('接取失败');
        ctx.body = 'false';
    });

});
// 查看自己的订单被谁接取了
router.get('/checkxs', async(ctx, next) => {
    if (ctx.request.querystring) {
        console.log('ctx.request.querystring', decodeURIComponent(ctx.request.querystring.split()));
        await userModel.findWhoxsPost(decodeURIComponent(ctx.request.querystring.split('=')[1]))
            .then(result => {
                res = JSON.parse(JSON.stringify(result));
                console.log(res);
            });

        await ctx.render('check', {
            session: ctx.session,
            posts: res
        });
    }
})
router.get('/showmyxs', async(ctx, next) => {
        var uid = ctx.session.id
        await userModel.findmyxsPost(uid).then(result => {
            res = JSON.parse(JSON.stringify(result))
        })
        await ctx.render('showmyxs', {
            session: ctx.session,
            posts: res

        });

    })
    //查看单篇文章
router.get('/posts/:postId', async(ctx, next) => {
    console.log(ctx.params.postId);
    // 通过文章id查找返回数据，然后增加pv 浏览 +1
    await userModel.findDataById(ctx.params.postId)
        .then(result => {
            res = JSON.parse(JSON.stringify(result));
            res_pv = parseInt(JSON.parse(JSON.stringify(result))[0]['pv']);
            res_pv += 1;
            console.log(res);
        });
    await userModel.updatePostPv([res_pv, ctx.params.postId]);
    await userModel.findCommentById(ctx.params.postId)
        .then(result => {
            comment_res = JSON.parse(JSON.stringify(result));
        });
    await userModel.fingCommentCount(ctx.params.postId).then(result => {
        comment_count = parseInt(JSON.parse(JSON.stringify(result))[0]['num']);
    });
    await ctx.render('sPost', {
        session: ctx.session,
        posts: res,
        comments: comment_res,
        number: comment_count
    });
});
//发表评论
router.post('/:postId', async(ctx, next) => {
    var name = ctx.session.user;
    var content = ctx.request.body.content;
    var postId = ctx.params.postId;
    //插入评论
    await userModel.insertComment([name, content, postId]);
    //获取文章评论数然后+1
    var res_comments;
    await userModel.findDataById(postId).then(result => {
        res_comments = parseInt(JSON.parse(JSON.stringify(result))[0]['comments']);
        res_comments++;
    });
    await userModel.updatePostComment([res_comments, postId]).then(() => {
        ctx.body = 'true';
        console.log('评论成功');
    }).catch(() => {
        ctx.body = 'false';
        console.log('评论失败');
    })
});
// 管理员删除评论
router.get('/admintalk/:postId/comment/:commentId/remove', async(ctx, next) => {
    var postId = ctx.params.postId;
    var commentId = ctx.params.commentId;
    //查找文章的评论数然后-1
    var res_comments;
    await userModel.findDataById(postId).then(result => {
        res_comments = parseInt(JSON.parse(JSON.stringify(result))[0]['comments']);
        console.log('comments', res_comments);
        res_comments--;
        console.log(res_comments);
    });
    //更新文章评论数
    await userModel.updatePostComment([res_comments, postId]);
    //删除对应评论
    await userModel.deleteComment(commentId).then(() => {
        ctx.body = {
            data: 1
        };
        console.log('删除评论成功');
    }).catch(() => {
        ctx.body = {
            data: 2
        };
        console.log('删除评论失败');
    });
});
//删除评论
router.get('/posts/:postId/comment/:commentId/remove', async(ctx, next) => {
    var postId = ctx.params.postId;
    var commentId = ctx.params.commentId;
    //查找文章的评论数然后-1
    var res_comments;
    await userModel.findDataById(postId).then(result => {
        res_comments = parseInt(JSON.parse(JSON.stringify(result))[0]['comments']);
        console.log('comments', res_comments);
        res_comments--;
        console.log(res_comments);
    });
    //更新文章评论数
    await userModel.updatePostComment([res_comments, postId]);
    //删除对应评论
    await userModel.deleteComment(commentId).then(() => {
        ctx.body = {
            data: 1
        };
        console.log('删除评论成功');
    }).catch(() => {
        ctx.body = {
            data: 2
        };
        console.log('删除评论失败');
    });
});
router.get('/admintalk/:postId/remove', async(ctx, next) => {
    var postId = ctx.params.postId;
    await userModel.deleteAllPostComment(postId);
    await userModel.deletePost(postId).then(() => {
        ctx.body = {
            data: 1
        };
        console.log('删除文章成功');
    }).catch(() => {
        ctx.body = {
            data: 2
        };
        console.log('删除文章失败');
    });
});
//删除文章
router.get('/posts/:postId/remove', async(ctx, next) => {
    var postId = ctx.params.postId;
    await userModel.deleteAllPostComment(postId);
    await userModel.deletePost(postId).then(() => {
        ctx.body = {
            data: 1
        };
        console.log('删除文章成功');
    }).catch(() => {
        ctx.body = {
            data: 2
        };
        console.log('删除文章失败');
    });
});
//编辑文章页面
router.get('/posts/:postId/edit', async(ctx, next) => {
    var postId = ctx.params.postId;
    await userModel.findDataById(postId).then(result => {
        res = JSON.parse(JSON.stringify(result));
        console.log('修改文章', res);
    });
    await ctx.render('edit', {
        session: ctx.session,
        posts: res
    });
});
// 删除悬赏
router.get('/xsposts/:postId/remove', async(ctx, next) => {
    var postId = ctx.params.postId;
    await userModel.deletexspost(postId).then(() => {
        ctx.body = {
            data: 1
        };
        console.log('删除悬赏成功');
    }).catch(() => {
        ctx.body = {
            data: 2
        };
        console.log('删除悬赏失败');
    });
});
// 管理员删除悬赏
router.get('/adminxspost/:postId/remove', async(ctx, next) => {
    var postId = ctx.params.postId;
    await userModel.deletexspost(postId).then(() => {
        ctx.body = {
            data: 1
        };
        console.log('删除悬赏成功');
    }).catch(() => {
        ctx.body = {
            data: 2
        };
        console.log('删除悬赏失败');
    });
});
// 编辑悬赏
router.get('/xsposts/:postId/edit1', async(ctx, next) => {
    var postId = ctx.params.postId;
    await userModel.findxsDataById(postId).then(result => {
        res = JSON.parse(JSON.stringify(result));
        console.log('修改悬赏贴', res);
    });
    await ctx.render('edit1', {
        session: ctx.session,
        posts: res
    });
});
//修改悬赏提交
router.post('/xsposts/:postId/edit1', async(ctx, next) => {
    var title = ctx.request.body.title;
    var content = ctx.request.body.content;
    var money = ctx.request.body.money;
    var postId = ctx.params.postId;
    console.log(title, content, money, postId);
    await userModel.updatexsPost([title, content, money, postId]).then(() => {
        ctx.body = 'true';
        console.log('修改悬赏成功');
    }).catch(() => {
        ctx.body = 'false';
        console.log('修改悬赏失败');
    });
});
router.get('/adminuser', async(ctx, next) => {
        await userModel.findAllUser().then(result => {
            console.log(result);
            res = JSON.parse(JSON.stringify(result));
            console.log(res);
        })
        await ctx.render('adminuser', {
            session: ctx.session,
            posts: res
        })
    })
    // 管理员删除用户
router.get('/adminuser/:postId/remove', async(ctx, next) => {
    var postId = ctx.params.postId;
    await userModel.deleteuser(postId).then(() => {
        ctx.redirect('/adminuser')
        console.log('删除用户成功');
    }).catch(() => {
        ctx.redirect('/adminuser')
        console.log('删除用户失败');
    });

});


//修改文章提交
router.post('/posts/:postId/edit', async(ctx, next) => {
    var title = ctx.request.body.title;
    var content = ctx.request.body.content;
    var id = ctx.session.id;
    var postId = ctx.params.postId;
    await userModel.updatePost([title, content, postId]).then(() => {
        ctx.body = 'true';
        console.log('修改文章成功');
    }).catch(() => {
        ctx.body = 'false';
        console.log('修改文章失败');
    });
});
module.exports = router;